import * as TYPES from "@/constants/index";
import * as UTILS from "@/utils/index";

import api from "@/api/index";
import { Toast } from "vant";

const state = {
  curBaby: {},
  allBaby: [],
};

const mutations = {
  [TYPES.CHANGE_CUR_BABY]: (state, payload) => {
    state.curBaby = payload;
  },
  [TYPES.CHANGE_ALL_BABY]: (state, payload) => {
    state.allBaby = payload;
  },
};

const actions = {
  //获取用户关联宝宝信息
  requestBabyItems: async ({ commit, rootState, rootGetters }, payload) => {
    try {
      const curDevice = rootGetters.device;
      const { params = {} } = payload;
      const { data } = await api.getBabyData(params);
      if (!data.success) throw new Error(data.info);

      //转化日期格式
      let items = UTILS.convertChildFormat(data.data);

      commit(TYPES.CHANGE_ALL_BABY, items);

      //初始化用户当前宝宝
      if (items.length < 1) commit(TYPES.CHANGE_CUR_BABY, {});
      let item = items.find((i) => i.isAuto * 1 === 1);
      let curItem = item ? item : items[0];

      commit(TYPES.CHANGE_CUR_BABY, curItem);
    } catch (err) {
      console.log(err);
      Toast.fail(err.message);
    }
  },

  //更换当前active宝宝
  updateActiveBaby: async ({ commit,dispatch }, payload) => {
    try {
      const { params } = payload;
      const { data } = await api.modifyBabyData(params);
      if (!data.success) throw new Error(data.info);

      dispatch('requestBabyItems', {
        params: {
          userId: params.userId
        }
      });
      Toast.success('切换宝宝成功!');
      
    } catch (err) {
      console.log(err);
      this.$toast.fail(err.message);
    }
  },
  //删除用户名下的某个baby
  deleteBaby: async ({ commit,dispatch }, payload) => { 
    try {
      const { id,userId } = payload
      const { data} = await api.deleteBabyData(id)
      if(!data.success) throw new Error(data.info);
      Toast.success("删除成功");

      dispatch('requestBabyItems', {params: {userId}});
    } catch (err) {
        console.log(err);
        this.$toast.fail(err.message);
    }
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
